package com.ccc.test.util;

import com.ccc.test.pojo.UrlLinkInfo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * URL链接工具类
 *
 * @author superC
 * @version 1.0.0
 * @date 2024/4/29
 */

public class UrlLinkUtil {
    protected static final Logger logger = LoggerFactory.getLogger(UrlLinkUtil.class);

    public static UrlLinkInfo getLinkInfo(String url) {
        UrlLinkInfo info = new UrlLinkInfo();
        try {
            // 先从一个URL加载一个Document对象。
            Document doc = Jsoup.connect(url).get();
            Elements head = doc.select("head");
            Elements titlelinks = head.get(0).select("title");
            String tilte = titlelinks.get(0).text();
            logger.info("tilte={}", tilte);
            info.setTitle(tilte);

            Element meta = doc.select("meta[name=description]").first();
            if (meta != null) {
                String description = meta.attr("content");
                logger.info("description={}", description);
                info.setDescription(description);
            } else {
                logger.info("【网址解析】 No description meta tag found.");
            }

            Elements links = doc.select("link[rel=icon]");
            // 通常情况下，第一个link标签就是logo的链接
            String logoUrl = links.size() > 0 ? links.get(0).absUrl("href") : "";
            logger.info("logoUrl={}", logoUrl);
            info.setLogo(logoUrl);

            logger.info("------------");
            logger.info("------------");

        } catch (Exception e) {
            logger.error("【捕获异常-网址解析】\r\n异常记录：", e);
        }
        return info;
    }

}
